package com.mj.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class Upload {
    //使用原名上传至指定文件夹
   /* @RequestMapping("/upload.do") @ResponseBody
    public void upl(@RequestParam("ff") CommonsMultipartFile cm, String fname) throws IOException {//requestparam一定要和input里面的name一致
        System.out.println(fname);
        String filename = cm.getOriginalFilename();
        cm.transferTo(new File("e:/",filename));
        System.out.printf("文件名字:%S<br>",filename);
        System.out.printf("文件大小:%d字节<br>",cm.getSize());
        System.out.printf("文件类型:%S",cm.getContentType());
    }*/
    @RequestMapping("/upload.do")
    @ResponseBody
    public ModelAndView upl(@RequestParam("ff") CommonsMultipartFile cm, String fname, HttpServletRequest request) throws IOException {//requestparam一定要和input里面的name一致
        ModelAndView mv = new ModelAndView("upinfo");
        String s = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String path = "/upload/" + s;
        String p = request.getServletContext().getRealPath(path);
        File fff = new File(p);
        if (!fff.exists()) {
            fff.mkdirs();
        }
        String nn = cm.getOriginalFilename();
        cm.transferTo(new File(p, nn));
        if (cm.isEmpty()) {
            mv.addObject("info", "未选择文件，上传失败");
        } else {
            mv.addObject("filename", cm.getOriginalFilename());
            mv.addObject("filesize", cm.getSize());
            mv.addObject("filetype", cm.getContentType());
            mv.addObject("formname", cm.getName());
        }
        return mv;
    }

    @RequestMapping("/upload.action")
    @ResponseBody
    public void upm(@RequestParam("fm") CommonsMultipartFile[] cmf) throws IOException {
        for (CommonsMultipartFile c : cmf) {
            if (c.isEmpty()) continue;
            c.transferTo(new File("e:/", c.getOriginalFilename()));
        }
    }
}
